package com.app.newiptv.promote;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.app.newiptv.R;
import com.app.newiptv.activity.HomePageActivity;
import com.app.newiptv.utils.APPLog;
import com.app.newiptv.utils.Paths;

import java.io.File;

public class SplashActivity extends Activity implements
		ConfigrationLoader.Callback, UpgradeUtil.DownloadListener {
	private ProgressBar progressBar;
	private TextView textView;
	private UpgradeHelper helper;
	private String appDir;
	private File upgradeAPK;
	private int max;
	private int progress;
	private TextView useNameText;
	private TextView useIdText;
	private Button sureButton;
	private RelativeLayout editRelative;
	private SharedPreferences sharePreference;
	private Runnable loadingDisplayText = new Runnable() {
		@Override
		public void run() {
			progressBar.setVisibility(View.VISIBLE);
			textView.setText("正在下载中....." + " " + progress + "/" + max);
		}
	};
	private Runnable loadFaildDisplayText = new Runnable() {
		@Override
		public void run() {
			progressBar.setVisibility(View.VISIBLE);
			textView.setText("");
		}
	};
	private Runnable lastVserionDisplayText = new Runnable() {
		@Override
		public void run() {
			progressBar.setVisibility(View.GONE);
			textView.setText("");
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash_layout);
		appDir = Environment.getExternalStorageDirectory().getPath()
				+ "/AHIPTVLauncher/download/";
		File folder = new File(appDir);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		System.out.println("appDir->" + appDir);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		textView = (TextView) findViewById(R.id.text);
		useNameText = (TextView) findViewById(R.id.name_edit);
		useIdText = (TextView) findViewById(R.id.use_edit);
		sureButton = (Button) findViewById(R.id.sure_button);
		editRelative = (RelativeLayout) findViewById(R.id.edit_relative);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		editRelative.setVisibility(View.GONE);
		ConfigrationLoader loader = new ConfigrationLoader();
		loader.setCallback(SplashActivity.this);
		loader.loadConfig(Paths.HOSTPATH + Paths.UPDATE_PAHT);
	}
	@Override
	public void onError(String code, String msg) {
		Toast.makeText(SplashActivity.this, "onError", Toast.LENGTH_SHORT).show();
		editInfo("usename","");
		editInfo("useid","");
	}

	@Override
	public void onCompleted() {
		helper = UpgradeHelper.getInstance();
		boolean flag = helper.checkVersion(SplashActivity.this);
		if (flag) {
			upgrade();
			APPLog.printInfo("开始更新");
		} else {
			editRelative.setVisibility(View.VISIBLE);
			APPLog.printInfo("updata已经是最新版本");
			sharePreference = getSharedPreferences("user",0);
			String useName = sharePreference.getString("usename","");
			String useId = sharePreference.getString("useid","");
			if(!(useName.equals("")||useId.equals(""))){
				editRelative.setVisibility(View.GONE);
				authAh(useName,useId);
			}
			sureButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					String useName =  useNameText.getText().toString();
					String useId = useIdText.getText().toString();
					//if(useName.equals("")||useId.equals("")){
					//	Toast.makeText(SplashActivity.this, "用户名或密码不能为空！", Toast.LENGTH_SHORT).show();
					//}else{
						editInfo("usename",useName);
						editInfo("useid",useId);
						authAh(useName,useId);
						Toast.makeText(SplashActivity.this, "useName"+useName +"useId" + useId, Toast.LENGTH_SHORT).show();
					//}
				}
			});
		}
	}

	private void upgrade() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					upgradeAPK = UpgradeUtil.upgrade(helper.getDownloadUrl(), appDir, SplashActivity.this);
				} catch (Exception e) {
					e.printStackTrace();
					APPLog.printInfo("下载失败");
				}
			}
		}).start();
	}

	@Override
	public void onLoading(int progress, int contentLen) {
		max = contentLen;
		this.progress = progress;
		textView.post(loadingDisplayText);
	}

	@Override
	public void onLoaded(File apk) {
		upgradeAPK = apk;
		UpgradeUtil.install(this, apk);
	}

	@Override
	public void onFailed() {
		APPLog.printInfo("apk下载失败，直接鉴权");
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(SplashActivity.this, "onFailed", Toast.LENGTH_SHORT).show();
			}
		});
	}
	private void authAh(String useName,String usePassword){
		AuthRunnable authRunnable = new AuthRunnable();
		authRunnable.setCallBack(new AuthCallBack() {
			@Override
			public void completeUpdateInfo() {
				//Toast.makeText(SplashActivity.this, "认证成功"+ Contast.USE_TOKEN, Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(SplashActivity.this, HomePageActivity.class);
				startActivity(intent);
				SplashActivity.this.finish();

			}

			@Override
			public void error() {
				Toast.makeText(SplashActivity.this, "认证失败", Toast.LENGTH_SHORT).show();
				editInfo("usename","");
				editInfo("useid","");
			}
		});
		authRunnable.loadData(Paths.HOSTPATH + Paths.AUTH,useName,usePassword);
	}
	private void editInfo(String key,String info){
		SharedPreferences.Editor editor = sharePreference.edit();
		editor.putString(key, info);
		editor.commit();
	}
}
